package com.gqh.weather.service;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gqh.weather.config.FileConfig;
import com.gqh.weather.config.MinioConfig;
import com.gqh.weather.domain.dto.MyPage;
import com.gqh.weather.domain.dto.PcSubTaskListDataDTO;
import com.gqh.weather.domain.dto.TaskSchedule;
import com.gqh.weather.domain.dto.StudentUploadAnswerData;
import com.gqh.weather.domain.dto.StudentScoreInfo;
import com.gqh.weather.domain.dto.PaperInfo;
import com.gqh.weather.domain.dto.AnswerData;
import com.gqh.weather.domain.entity.PcSubtask;
import com.gqh.weather.domain.entity.Task;
import com.gqh.weather.domain.entity.Student;
import com.gqh.weather.domain.entity.StudentAnswer;
import com.gqh.weather.domain.entity.YjStudentAnswerScore;
import com.gqh.weather.domain.entity.School;
import com.gqh.weather.domain.enums.XuekeEnum;
import com.gqh.weather.domain.enums.NianjiEnum;
import com.gqh.weather.mapper.PcSubtaskMapper;
import com.gqh.weather.mapper.TaskMapper;
import com.gqh.weather.mapper.StudentMapper;
import com.gqh.weather.mapper.StudentAnswerMapper;
import com.gqh.weather.mapper.YjStudentAnswerScoreMapper;
import com.gqh.weather.mapper.SchoolMapper;
import com.gqh.weather.util.MinioUtil;

import io.minio.MinioClient;
import io.minio.PutObjectArgs;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;

/**
 * @description PC端子任务管理服务类
 * @author AI
 * @date 2025-09-21
 */
@Slf4j
@Service
public class PcSubtaskService extends ServiceImpl<PcSubtaskMapper, PcSubtask> {
    
    @Autowired
    private PcSubtaskMapper pcSubtaskMapper;
    
    @Autowired
    private TaskMapper taskMapper;
    
//    @Autowired
//    private StudentSubjectiveAnswerMapper studentSubjectiveAnswerMapper;
    
    @Autowired
    private StudentMapper studentMapper;
    
    @Autowired
    @Lazy
    private TaskService taskService;
    
    @Autowired
    private PcExamPackageService pcExamPackageService;
    
    @Autowired
    private AnswerSheetService answerSheetService;
    
    @Autowired
    private FileConfig fileConfig;
    
    @Autowired
    private MinioConfig minioConfig;
    
    @Autowired
    private MinioUtil minioUtil;
    
    @Autowired
    private MinioClient minioClient;
    
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    
    @Autowired
    private StudentAnswerMapper studentAnswerMapper;
    
    @Autowired
    private YjStudentAnswerScoreMapper yjStudentAnswerScoreMapper;
    
    @Autowired
    private PaperService paperService;
    
    @Autowired
    private SchoolMapper schoolMapper;
    
    // 用于JSON解析
    private static final ObjectMapper objectMapper = new ObjectMapper();
    
    // ZIP文件密码
    private static final String ZIP_PASSWORD = "k5Xk@lDv7S8^iliQiemK#kGtDsSER@HE";
    
    /**
     * 根据父任务ID结束子任务
     *
     * @param taskPid 父任务ID
     * @param state 状态
     * @return 是否成功
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean endSubtaskByTaskPid(Integer taskPid, Integer state) {
        try {
            // 查询对应的子任务
            LambdaQueryWrapper<PcSubtask> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(PcSubtask::getTaskPid, taskPid);
            PcSubtask pcSubtask = getOne(wrapper);
            
            if (pcSubtask == null) {
                log.warn("未找到对应的子任务，父任务ID: {}", taskPid);
                return false;
            }
            
            // 更新子任务状态
            return updatePcSubtaskState(pcSubtask.getId(), state);
        } catch (Exception e) {
            log.error("根据父任务ID结束子任务失败，父任务ID: " + taskPid, e);
            return false;
        }
    }

    /**
     * 创建子任务
     *
     * @param taskPid 父任务ID
     * @return 是否成功
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean createSubtask(Integer taskPid, Integer type, String schedule) {
        try {
            // 检查是否已存在对应的子任务
            LambdaQueryWrapper<PcSubtask> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(PcSubtask::getTaskPid, taskPid);
            PcSubtask existingSubtask = getOne(wrapper);
            
            if (existingSubtask != null) {
                log.warn("子任务已存在，父任务ID: {}", taskPid);
                return true;
            }
            
            // 创建新的子任务
            PcSubtask pcSubtask = new PcSubtask();
            pcSubtask.setTaskPid(taskPid);
            pcSubtask.setState(0); // 默认未发布状态
            pcSubtask.setYjState(0); // 默认未阅卷状态
            pcSubtask.setType(type);
            pcSubtask.setSchedule(schedule); // 默认未阅卷状态

            return save(pcSubtask);
        } catch (Exception e) {
            log.error("创建子任务失败，父任务ID: " + taskPid, e);
            return false;
        }
    }

    /**
     * 更新PC子任务状态
     *
     * @param id PC子任务ID
     * @param state 状态：0未发布 1已发布 2结束
     * @return 更新结果
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean updatePcSubtaskState(Integer id, Integer state) {
        PcSubtask pcSubtask = getById(id);
        if (pcSubtask == null) {
            return false;
        }
        
        // 如果状态从其他状态变为1（已发布），需要生成考务包和答题卡
        if (state == 1 && pcSubtask.getState() != 1) {
            // 生成考务包
//            pcExamPackageService.genExamPackage(id);
            
            // 异步生成答题卡
//            answerSheetService.genAnswerSheetAsync(id, taskService, this);
        } else if (state == 2 && pcSubtask.getState() != 2) {
            // 如果状态变为2（结束），需要计算分数
            calculateScore(id);
            
            // 更新阅卷状态为已结束
            PcSubtask updateSubtask = new PcSubtask();
            updateSubtask.setId(id);
            updateSubtask.setYjState(2);
            updateById(updateSubtask);
        }
        
        pcSubtask.setState(state);
        return updateById(pcSubtask);
    }
    
    /**
     * 计算分数
     *
     * @param id PC子任务ID
     */
    private void calculateScore(Integer id) {
        try {
            // 获取PC子任务信息
            PcSubtask pcSubtask = getById(id);
            if (pcSubtask == null) {
                log.error("PC子任务不存在，ID: {}", id);
                return;
            }
            
            // 检查是否需要阅卷
            if (pcSubtask.getType() == 1 && pcSubtask.getYjState() == 0) {
                log.error("考评尚未阅卷，ID: {}", id);
                throw new RuntimeException("考评尚未阅卷");
            }
            
            // 获取关联的任务ID
            Integer taskId = pcSubtask.getTaskPid();
            
            // 查询所有学生答案记录
            LambdaQueryWrapper<StudentAnswer> answerWrapper = new LambdaQueryWrapper<>();
            answerWrapper.eq(StudentAnswer::getTaskId, taskId);
            answerWrapper.eq(StudentAnswer::getIsDeleted, 0);
            List<StudentAnswer> answers = studentAnswerMapper.selectList(answerWrapper);
            
            if (answers == null || answers.isEmpty()) {
                log.info("没有找到学生答案记录，任务ID: {}", taskId);
                return;
            }
            
            // 使用并行处理提高性能
            answers.parallelStream().forEach(answer -> {
                try {
                    // 解析答案数据
                    List<StudentUploadAnswerData> resAnswers = new ArrayList<>();
                    if (answer.getAnswer() != null && !answer.getAnswer().isEmpty()) {
                        resAnswers = objectMapper.readValue(answer.getAnswer(), 
                            new TypeReference<List<StudentUploadAnswerData>>() {});
                    }
                    
                    // 计算分数
                    StudentAnswer answerScore = countScore(answer.getId(), answer.getPaperId(), resAnswers);
                    
                    // 更新学生答案记录的分数
                    studentAnswerMapper.updateById(answerScore);
                } catch (Exception e) {
                    log.error("计算学生答案分数失败，answerId: {}", answer.getId(), e);
                }
            });
            
            log.info("计算分数完成，ID: {}", id);
        } catch (Exception e) {
            log.error("计算分数失败，ID: {}", id, e);
            throw new RuntimeException("计算分数失败: " + e.getMessage());
        }
    }
    
    /**
     * 计算单个学生答案的分数
     *
     * @param answerId 答案ID
     * @param paperId 试卷ID
     * @param resAnswers 学生答案列表
     * @return 学生答案对象（包含分数信息）
     */
    private StudentAnswer countScore(Integer answerId, Integer paperId, List<StudentUploadAnswerData> resAnswers) {
        try {
            double countScore = 0.0;
            double zgCountScore = 0.0;
            Map<Integer, StudentScoreInfo> mapAnswers = new HashMap<>();
            
            // 构建答案映射
            for (StudentUploadAnswerData ra : resAnswers) {
                StudentScoreInfo scoreInfo = new StudentScoreInfo();
                scoreInfo.setQid(ra.getQid());
                scoreInfo.setAnswer(ra.getAnswer());
                mapAnswers.put(ra.getQid(), scoreInfo);
            }
            
            // 获取试卷信息
            PaperInfo paperInfo = paperService.getPaperInfo(paperId).getData();
            if (paperInfo == null) {
                throw new RuntimeException("找不到对应科目试卷");
            }
            
            // 先处理综合题（qtype=100）
            if (paperInfo.getDataInfo() != null) {
                for (PaperInfo.PaperInfoData pd : paperInfo.getDataInfo()) {
                    if (pd.getQinfos() != null) {
                        for (PaperInfo.QuestionInfos qinfo : pd.getQinfos()) {
                            if ("100".equals(pd.getQtype())) { // 综合题
                                if (qinfo.getSubIDInfos() != null) {
                                    for (PaperInfo.QuestionData subIdInfo : qinfo.getSubIDInfos()) {
                                        StudentScoreInfo scoreInfo = mapAnswers.get(subIdInfo.getId());
                                        if (scoreInfo == null) {
                                            scoreInfo = new StudentScoreInfo();
                                            scoreInfo.setQid(subIdInfo.getId());
                                            mapAnswers.put(subIdInfo.getId(), scoreInfo);
                                        }
                                        scoreInfo.setBaseAnswer(subIdInfo.getAnswer());
                                        scoreInfo.setQtype(subIdInfo.getQtype());
                                        
                                        double singleScore = parseDouble(pd.getSingleScore());
                                        double qNum = parseDouble(pd.getQnum());
                                        scoreInfo.setMaxScore(roundPrecision(singleScore / qNum, 1));
                                        
                                        if (subIdInfo.getQtype() > 0 && subIdInfo.getQtype() <= 4) {
                                            if (equalsIgnoreCase(subIdInfo.getAnswer(), scoreInfo.getAnswer())) {
                                                scoreInfo.setScore(scoreInfo.getMaxScore());
                                            }
                                        }
                                        countScore += scoreInfo.getScore();
                                    }
                                }
                            }
                        }
                    }
                }
                
                // 处理其他题型
                for (PaperInfo.PaperInfoData pd : paperInfo.getDataInfo()) {
                    if (pd.getQinfos() != null) {
                        for (PaperInfo.QuestionInfos qinfo : pd.getQinfos()) {
                            // 综合题 已经处理过
                            if ("100".equals(pd.getQtype())) {
                                continue;
                            }
                            // 主观题
                            if ("99".equals(pd.getQtype())) {
                                StudentScoreInfo scoreInfo = mapAnswers.get(qinfo.getId());
                                if (scoreInfo == null) {
                                    scoreInfo = new StudentScoreInfo();
                                    scoreInfo.setQid(qinfo.getId());
                                    mapAnswers.put(qinfo.getId(), scoreInfo);
                                }
                                scoreInfo.setQtype(qinfo.getQtype());
                                scoreInfo.setMaxScore(parseDouble(pd.getSingleScore()));
                                
                                // 从zh_student_answer_score表查询主观题分数
                                // 按照st_role的顺序2>1>0获取分数
                                Double subjectiveScore = getSubjectiveScore(answerId, qinfo.getId());
                                if (subjectiveScore != null) {
                                    scoreInfo.setScore(subjectiveScore);
                                    zgCountScore += subjectiveScore;
                                }
                            } else if ("1".equals(pd.getQtype()) || 
                                "2".equals(pd.getQtype()) || 
                                "3".equals(pd.getQtype()) || 
                                "4".equals(pd.getQtype()) || 
                                "5".equals(pd.getQtype())) {
                                
                                StudentScoreInfo scoreInfo = mapAnswers.get(qinfo.getId());
                                if (scoreInfo == null) {
                                    scoreInfo = new StudentScoreInfo();
                                    scoreInfo.setQid(qinfo.getId());
                                    mapAnswers.put(qinfo.getId(), scoreInfo);
                                }
                                scoreInfo.setQtype(qinfo.getQtype());
                                scoreInfo.setMaxScore(parseDouble(pd.getSingleScore()));
                                
                                if (qinfo.getQtype() == 1 && qinfo.getStype() == 1) {
                                    // 程度分
                                    scoreInfo.setScore(0.0);
                                    
                                    if (qinfo.getData() != null && !qinfo.getData().isEmpty()) {
                                        List<AnswerData> answerData = objectMapper.readValue(
                                            qinfo.getData(), 
                                            new TypeReference<List<AnswerData>>() {});
                                        
                                        for (AnswerData ad : answerData) {
                                            if (equalsIgnoreCase(ad.getId(), scoreInfo.getAnswer())) {
                                                double adScore = parseDouble(ad.getScore());
                                                scoreInfo.setScore(roundPrecision((adScore * scoreInfo.getMaxScore()) / 100, 1));
                                            }
                                        }
                                    }
                                } else {
                                    // 对于连线题(qtype=5)，需要特殊处理答案比较
                                    if (qinfo.getQtype() == 5) {
                                        scoreInfo.setBaseAnswer(qinfo.getAnswer());
                                        if (isMatchingConnectionAnswer(qinfo.getAnswer(), scoreInfo.getAnswer())) {
                                            scoreInfo.setScore(scoreInfo.getMaxScore());
                                        }
                                    } else {
                                        scoreInfo.setBaseAnswer(qinfo.getAnswer());
                                        if (equalsIgnoreCase(qinfo.getAnswer(), scoreInfo.getAnswer())) {
                                            scoreInfo.setScore(scoreInfo.getMaxScore());
                                        }
                                    }
                                }
                                countScore += scoreInfo.getScore();
                            }
                        }
                    }
                }
            }
            
            // 根据qid排序
            List<Integer> sqids = new ArrayList<>(mapAnswers.keySet());
            Collections.sort(sqids);
            
            List<StudentScoreInfo> scoreInfoList = new ArrayList<>();
            List<StudentScoreInfo> zgScoreInfoList = new ArrayList<>(); // 用于存储主观题信息
            for (Integer sqid : sqids) {
                StudentScoreInfo scoreInfo = mapAnswers.get(sqid);
                // 过滤掉主观题（qtype=99），scoreData只存储非主观题的信息
                if (scoreInfo.getQtype() != null && scoreInfo.getQtype() != 99) {
                    scoreInfoList.add(scoreInfo);
                } else if (scoreInfo.getQtype() != null && scoreInfo.getQtype() == 99) {
                    // 主观题信息存储到zgScoreInfoList中
                    zgScoreInfoList.add(scoreInfo);
                }
            }
            
            String scoreData = "";
            if (!scoreInfoList.isEmpty()) {
                scoreData = objectMapper.writeValueAsString(scoreInfoList);
            }
            
            String zgScoreData = ""; // 主观题评分数据
            if (!zgScoreInfoList.isEmpty()) {
                zgScoreData = objectMapper.writeValueAsString(zgScoreInfoList);
            }
            
            StudentAnswer studentAnswer = new StudentAnswer();
            studentAnswer.setId(answerId);
            studentAnswer.setScore(countScore);
            studentAnswer.setScoreData(scoreData);
            
            studentAnswer.setZgscore(zgCountScore);
            studentAnswer.setZgscoreData(zgScoreData); // 设置主观题评分数据
            
            return studentAnswer;
        } catch (Exception e) {
            log.error("计算分数失败，answerId: {}", answerId, e);
            throw new RuntimeException("计算分数失败: " + e.getMessage());
        }
    }
    
    /**
     * 解析字符串为double值
     *
     * @param value 字符串值
     * @return double值
     */
    private double parseDouble(String value) {
        if (value == null || value.isEmpty()) {
            return 0.0;
        }
        try {
            return Double.parseDouble(value);
        } catch (NumberFormatException e) {
            return 0.0;
        }
    }
    
    /**
     * 比较两个字符串是否相等（忽略大小写）
     *
     * @param str1 字符串1
     * @param str2 字符串2
     * @return 是否相等
     */
    private boolean equalsIgnoreCase(String str1, String str2) {
        if (str1 == null && str2 == null) {
            return true;
        }
        if (str1 == null || str2 == null) {
            return false;
        }
        return str1.equalsIgnoreCase(str2);
    }
    
    /**
     * 四舍五入到指定精度
     *
     * @param value 值
     * @param precision 精度
     * @return 四舍五入后的值
     */
    private double roundPrecision(double value, int precision) {
        BigDecimal bd = new BigDecimal(Double.toString(value));
        bd = bd.setScale(precision, RoundingMode.HALF_UP);
        return bd.doubleValue();
    }
    
    /**
     * 比较连线题答案是否匹配
     * 连线题答案格式为"1-2,2-3,3-1"，需要按逗号分组并排序后比较
     *
     * @param baseAnswer 标准答案
     * @param studentAnswer 学生答案
     * @return 是否匹配
     */
    private boolean isMatchingConnectionAnswer(String baseAnswer, String studentAnswer) {
        if (baseAnswer == null && studentAnswer == null) {
            return true;
        }
        if (baseAnswer == null || studentAnswer == null) {
            return false;
        }
        
        // 按逗号分割并排序
        String sortedBaseAnswer = sortConnectionAnswer(baseAnswer);
        String sortedStudentAnswer = sortConnectionAnswer(studentAnswer);
        
        return sortedBaseAnswer.equals(sortedStudentAnswer);
    }
    
    /**
     * 对连线题答案进行排序
     * 将"1-2,2-3,3-1"转换为排序后的"1-2,2-3,3-1"
     *
     * @param answer 答案字符串
     * @return 排序后的答案字符串
     */
    private String sortConnectionAnswer(String answer) {
        if (answer == null || answer.isEmpty()) {
            return answer;
        }
        
        // 按逗号分割
        String[] parts = answer.split(",");
        
        // 对每个部分进行排序
        Arrays.sort(parts);
        
        // 重新组合
        return String.join(",", parts);
    }
    
    /**
     * 获取主观题分数
     * 按照st_role的顺序2>1>0获取分数
     *
     * @param answerId 答案ID
     * @param qid 题目ID
     * @return 分数
     */
    private Double getSubjectiveScore(Integer answerId, Integer qid) {
        try {
            // 查询学生答案记录以获取studentId
            StudentAnswer studentAnswer = studentAnswerMapper.selectById(answerId);
            if (studentAnswer == null) {
                return null;
            }
            
            Integer studentId = studentAnswer.getStudentId();
            
            // 使用一条SQL查询，按st_role优先级排序(2>1>0)
            LambdaQueryWrapper<YjStudentAnswerScore> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(YjStudentAnswerScore::getStudentId, studentId)
                   .eq(YjStudentAnswerScore::getQid, qid)
                   .eq(YjStudentAnswerScore::getIsDeleted, 0)
                   .orderByDesc(YjStudentAnswerScore::getStRole)  // 按st_role降序排列，优先级：2>1>0
                   .last("LIMIT 1");  // 只取第一条记录
            
            YjStudentAnswerScore score = yjStudentAnswerScoreMapper.selectOne(wrapper);
            
            return score != null ? score.getScore() : null;
        } catch (Exception e) {
            log.error("获取主观题分数失败，answerId: {}, qid: {}", answerId, qid, e);
            return null;
        }
    }
    
    /**
     * 获取PC子任务列表
     *
     * @param page 页码
     * @param count 每页数量
     * @param keyword 关键字
     * @param uid 用户ID
     * @return PC子任务列表响应
     */
    public MyPage<PcSubTaskListDataDTO> getPcSubtaskList(Integer page, Integer count, String keyword, Integer uid) {
        // 创建分页对象
        Page<PcSubTaskListDataDTO> pageObj = new Page<>(page, count);
        
        // 调用Mapper方法查询数据
        Page<PcSubTaskListDataDTO> result = pcSubtaskMapper.selectPcSubtaskListWithTaskInfo(pageObj, uid, keyword, null);
        
        // 转换为MyPage对象
        MyPage<PcSubTaskListDataDTO> response = new MyPage<>();
        response.setPage(page);
        response.setCount(count);
        response.setTotal(result.getTotal());
        response.setData(result.getRecords());
        
        // 为每个子任务计算上传进度
//        for (PcSubTaskListDataDTO subtask : response.getData()) {
//            // 只有已发布的任务才计算上传进度
//            if (subtask.getState() != null && subtask.getState() != 0) {
//                subtask.setUploadProgress(calculateUploadProgress(subtask, uid));
//            } else {
//                subtask.setUploadProgress(new PcSubTaskUploadProgressDTO[0]);
//            }
//        }
        
        return response;
    }
    
    /**
     * 获取PC子任务详情
     *
     * @param id PC子任务ID
     * @return PC子任务详情数据传输对象
     */
    public PcSubTaskListDataDTO getPcSubtaskInfo(Integer id) {
        return pcSubtaskMapper.selectPcSubtaskInfoWithTaskInfo(id);
    }
    
    /**
     * 计算上传进度
     *
     * @param subtask 子任务信息
     * @param uid 用户ID
     * @return 上传进度数组
     */
//    private PcSubTaskUploadProgressDTO[] calculateUploadProgress(PcSubTaskListDataDTO subtask, Integer uid) {
//        List<PcSubTaskUploadProgressDTO> progressList = new ArrayList<>();
//
//        try {
//            // 获取学生总数
//            LambdaQueryWrapper<Task> taskWrapper = new LambdaQueryWrapper<>();
//            taskWrapper.eq(Task::getId, subtask.getTaskPid());
//            Task task = taskMapper.selectOne(taskWrapper);
//
//            if (task != null) {
//                int studentCount = task.getStudentCount() != null ? task.getStudentCount() : 0;
//
//                // 解析学科信息
//                if (subtask.getSchedule() != null && !subtask.getSchedule().isEmpty() && !subtask.getSchedule().equals("[]")) {
//                    // 解析schedule JSON数组
//                    List<Map<String, Object>> schedules = objectMapper.readValue(subtask.getSchedule(),
//                            new TypeReference<List<Map<String, Object>>>() {});
//
//                    for (Map<String, Object> schedule : schedules) {
//                        String paperType = (String) schedule.get("Type");
//                        if (paperType != null && !paperType.isEmpty()) {
//                            PcSubTaskUploadProgressDTO progress = new PcSubTaskUploadProgressDTO();
//                            progress.setPaperType(paperType);
//                            progress.setTotal(studentCount);
//
//                            // 查询已上传人数
//                            LambdaQueryWrapper<StudentSubjectiveAnswer> answerWrapper = new LambdaQueryWrapper<>();
//                            answerWrapper.eq(StudentSubjectiveAnswer::getPcSubtaskId, subtask.getId());
//                            answerWrapper.eq(StudentSubjectiveAnswer::getPaperType, Integer.parseInt(paperType));
//                            answerWrapper.eq(StudentSubjectiveAnswer::getIsDeleted, 0);
//                            int uploadCount = Math.toIntExact(studentSubjectiveAnswerMapper.selectCount(answerWrapper));
//
//                            progress.setUploadCount(uploadCount);
//                            progressList.add(progress);
//                        }
//                    }
//                }
//            }
//        } catch (Exception e) {
//            // 解析失败时返回空数组
//            return new PcSubTaskUploadProgressDTO[0];
//        }
//
//        return progressList.toArray(new PcSubTaskUploadProgressDTO[0]);
//    }
    
    /**
     * 设置阅卷老师配置数据
     *
     * @param pcSubtaskId PC子任务ID
     * @param configData 配置数据
     * @return 更新结果
     */
    public boolean setScoreTeacherConfig(Integer pcSubtaskId, String configData) {
        PcSubtask pcSubtask = new PcSubtask();
        pcSubtask.setId(pcSubtaskId);
        pcSubtask.setScoreTeacher(configData);
        pcSubtask.setYjState(1);
        return updateById(pcSubtask);
    }
    
    /**
     * 获取答题卡生成状态
     *
     * @param id PC子任务ID
     * @return 状态信息
     */
    public Map<String, Object> getAnswerSheetState(Integer id) {
        try {
            String key = "gen_answer_sheet:task_" + id;
            String stateJson = redisTemplate.opsForValue().get(key);
            
            if (stateJson != null && !stateJson.isEmpty()) {
                // 解析Redis中的状态JSON
                return objectMapper.readValue(stateJson, new TypeReference<Map<String, Object>>() {});
            } else {
                // 如果Redis中没有状态，返回默认状态（未生成）
                Map<String, Object> defaultState = new HashMap<>();
                defaultState.put("code", 2); // 无任务或无学生
                defaultState.put("msg", "未找到生成状态");
                return defaultState;
            }
        } catch (Exception e) {
            log.error("获取答题卡生成状态失败，ID: {}", id, e);
            // 发生异常时返回错误状态
            Map<String, Object> errorState = new HashMap<>();
            errorState.put("code", 3); // 生成失败
            errorState.put("msg", "获取状态异常: " + e.getMessage());
            return errorState;
        }
    }
    
    /**
     * 设置阅卷状态
     *
     * @param pcSubtaskId PC子任务ID
     * @param yjState 阅卷状态
     * @return 更新结果
     */
    public boolean setYjState(Integer pcSubtaskId, Integer yjState) {
        PcSubtask pcSubtask = new PcSubtask();
        pcSubtask.setId(pcSubtaskId);
        pcSubtask.setYjState(yjState);
        return updateById(pcSubtask);
    }
    
    /**
     * 设置复评状态
     *
     * @param pcSubtaskId PC子任务ID
     * @param fpState 复评状态
     * @return 更新结果
     */
    public boolean setFpState(Integer pcSubtaskId, Integer fpState) {
        PcSubtask pcSubtask = new PcSubtask();
        pcSubtask.setId(pcSubtaskId);
        pcSubtask.setFpState(fpState);
        return updateById(pcSubtask);
    }
    
    /**
     * 导出学业成绩
     *
     * @param id PC子任务ID
     * @param citycode 城市码
     * @param isPsyc 是否为心理科目
     * @return 导出文件的URL
     */
    public String exportScore(Integer id, String citycode, boolean isPsyc) throws Exception {
        // 获取PC子任务信息
        PcSubtask pcSubtask = getById(id);
        if (pcSubtask == null) {
            throw new RuntimeException("PC子任务不存在");
        }
        
        // 获取关联的任务信息
        Task task = taskService.getById(pcSubtask.getTaskPid());
        if (task == null) {
            throw new RuntimeException("关联的任务不存在");
        }
        
        // 解析日程信息
        List<TaskSchedule> schedules = new ArrayList<>();
        if (pcSubtask.getSchedule() != null && !pcSubtask.getSchedule().isEmpty()) {
            schedules = objectMapper.readValue(pcSubtask.getSchedule(), 
                new TypeReference<List<TaskSchedule>>() {});
        }
        
        // 获取学科类型列表
        List<Integer> xuekeTypes = new ArrayList<>();
        for (TaskSchedule schedule : schedules) {
            if (isPsyc && "400".equals(schedule.getType())) {
                xuekeTypes.add(400);
            } else if (!isPsyc && 
                ("200".equals(schedule.getType()) || 
                 "201".equals(schedule.getType()) || 
                 "202".equals(schedule.getType()) || 
                 "203".equals(schedule.getType()) || 
                 "204".equals(schedule.getType()))) {
                int xuekeType = Integer.parseInt(schedule.getType());
                if (!xuekeTypes.contains(xuekeType)) {
                    xuekeTypes.add(xuekeType);
                }
            }
        }
        
        if (xuekeTypes.isEmpty()) {
            if (isPsyc) {
                throw new RuntimeException("该考务无心理健康科目");
            } else {
                throw new RuntimeException("该考务无学业科目");
            }
        }
        
        // 获取学生列表
        LambdaQueryWrapper<Student> studentWrapper = new LambdaQueryWrapper<>();
        studentWrapper.eq(Student::getTaskId, task.getId());
        studentWrapper.eq(Student::getIsDeleted, 0);
        List<Student> students = studentMapper.selectList(studentWrapper);
        
        // 获取学生答案列表
        LambdaQueryWrapper<StudentAnswer> answerWrapper = new LambdaQueryWrapper<>();
        answerWrapper.eq(StudentAnswer::getTaskId, task.getId());
        answerWrapper.eq(StudentAnswer::getIsDeleted, 0);
        List<StudentAnswer> answers = studentAnswerMapper.selectList(answerWrapper);
        
        // 构建答案映射
        Map<Integer, Map<Integer, StudentAnswer>> studentAnswersMap = new HashMap<>();
        for (StudentAnswer answer : answers) {
            studentAnswersMap.computeIfAbsent(answer.getStudentId(), k -> new HashMap<>())
                .put(answer.getPaperType(), answer);
        }
        
        // 创建导出数据
        List<List<Object>> exportData = new ArrayList<>();
        
        // 表头
        List<Object> header = new ArrayList<>();
        header.add("所在学校");
        header.add("姓名");
        header.add("性别");
        header.add("学籍号");
        header.add("年级");

        if (!isPsyc) {
            header.add("总分");
        }
        
        for (Integer xuekeType : xuekeTypes) {
            // 使用XuekeEnum转换学科代码为学科名称
            String xuekeName = XuekeEnum.getDescription(xuekeType);
            header.add(xuekeName + "总分");
            header.add(xuekeName + "客观题");
            header.add(xuekeName + "主观题");
        }
        
        exportData.add(header);
        
        // 数据行
        for (Student student : students) {
            List<Object> row = new ArrayList<>();
            // 获取学校名称
            String schoolName = "";
            if (student.getSchoolId() != null) {
                School school = schoolMapper.selectById(student.getSchoolId());
                if (school != null) {
                    schoolName = school.getName();
                }
            }
            row.add(schoolName);
            row.add(student.getName());
            row.add(student.getSex() == 1 ? "男" : "女");
            row.add(student.getStudentNo());
            // 使用NianjiEnum转换年级代码为年级名称
            row.add(NianjiEnum.getDescription(student.getGrade()));

            if (!isPsyc) {
                row.add(""); // 总分
            }

            double totalScore = 0;
            
            Map<Integer, StudentAnswer> studentAnswerMap = studentAnswersMap.getOrDefault(student.getId(), new HashMap<>());
            for (Integer xuekeType : xuekeTypes) {
                StudentAnswer answer = studentAnswerMap.get(xuekeType);
                if (answer != null) {
                    totalScore = totalScore + answer.getScore() + answer.getZgscore();
                    row.add(answer.getScore() + answer.getZgscore()); // 总分
                    row.add(answer.getScore()); // 客观题分数
                    row.add(answer.getZgscore()); // 主观题分数
                } else {
                    row.add(0); // 总分
                    row.add(0); // 客观题分数
                    row.add(0); // 主观题分数
                }
            }

            row.set(5, totalScore);
            
            exportData.add(row);
        }
        
        // 生成文件名
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));
        String fileName = (isPsyc ? "心理成绩" : "学业成绩") + "_" + timestamp + ".xlsx";
        String filePath = Paths.get(fileConfig.getExportDir(), fileName).toString();
        
        // 创建目录
        File exportDir = new File(fileConfig.getExportDir());
        if (!exportDir.exists()) {
            exportDir.mkdirs();
        }
        
        // 导出Excel文件
        EasyExcel.write(filePath).sheet("成绩列表").doWrite(exportData);
        
        // 上传文件到MinIO的temp存储桶
        File file = new File(filePath);
        String objectName = fileName;
        
        try (FileInputStream fis = new FileInputStream(file)) {
            minioClient.putObject(
                PutObjectArgs.builder()
                    .bucket(minioConfig.getTemp()) // 使用现有的存储桶
                    .object(objectName)
                    .stream(fis, file.length(), -1)
                    .contentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
                    .build()
            );
        }
        
        // 删除本地文件
        file.delete();
        
        // 返回MinIO文件URL
        return "/files/" + minioConfig.getTemp() + "/" + objectName;
    }
}